// 创建Vue应用
new Vue({
    el: '#app',
    data() {
        return {
            // UI状态
            isCollapse: false,
            // 代理列表数据
            proxies: [],
            // 加载状态
            loading: false,
            // 提交状态
            submitLoading: false,
            // 分页信息
            pagination: {
                page: 1,
                pageSize: 10,
                total: 0
            },
            // 筛选条件
            filters: {
                proxyIP: '',
                proxyUser: '',
                proxyType: ''
            },
            // 对话框显示状态
            proxyDialogVisible: false,
            syncDialogVisible: false,
            applyProxyDialogVisible: false,
            // 编辑模式（true为编辑，false为新增）
            isEditMode: false,
            // 对话框标题
            dialogTitle: '添加代理',
            // 当前编辑的代理表单
            proxyForm: {
                id: '',  // 仅编辑时使用
                proxyType: 'http',
                proxyIP: '',
                proxyPort: '',
                proxyUser: '',
                proxyPassword: '',
                proxyTagID: '',
                note: ''
            },
            // 表单验证规则
            proxyRules: {
                proxyType: [
                    { required: true, message: '请选择代理类型', trigger: 'change' }
                ],
                proxyIP: [
                    { required: true, message: '请输入代理IP', trigger: 'blur' },
                    { pattern: /^(\d{1,3}\.){3}\d{1,3}$|([\w-]+\.)+[\w-]+/, message: '请输入有效的IP地址或域名', trigger: 'blur' }
                ],
                proxyPort: [
                    { required: true, message: '请输入代理端口', trigger: 'blur' },
                    { pattern: /^\d+$/, message: '端口必须是数字', trigger: 'blur' }
                ]
            },
            // 同步结果
            syncResult: null,
            
            // 应用代理相关数据
            currentProxy: null,
            users: [],
            selectedUsers: [],
            userSearchKeyword: '',
            selectAllUsers: false,
            applyLoading: false,
            applyResult: []
        };
    },
    created() {
        // 页面创建时加载代理列表
        this.loadProxies();
    },
    computed: {
        // 过滤后的用户列表
        filteredUsers() {
            if (!this.userSearchKeyword) {
                return this.users;
            }
            
            const keyword = this.userSearchKeyword.toLowerCase();
            return this.users.filter(user => 
                user.username.toLowerCase().includes(keyword)
            );
        }
    },
    methods: {
        // 导航到其他页面
        navigateTo(path) {
            window.location.href = path;
        },
        
        // 切换侧边栏折叠状态
        toggleSidebar() {
            this.isCollapse = !this.isCollapse;
        },
        
        // 根据代理类型获取标签颜色类型
        getProxyTypeTagType(type) {
            if (!type) return 'info';
            const typeMap = {
                'http': 'primary',
                'socks5': 'success',
                'ssh': 'warning'
            };
            return typeMap[type.toLowerCase()] || 'info';
        },
        
        // 重置筛选条件
        resetFilters() {
            this.filters = {
                proxyIP: '',
                proxyUser: '',
                proxyType: ''
            };
            this.loadProxies();
        },
        
        // 加载代理列表
        loadProxies() {
            this.loading = true;
            
            const params = {
                page: this.pagination.page,
                pageSize: this.pagination.pageSize,
                proxyIP: this.filters.proxyIP,
                proxyUser: this.filters.proxyUser,
                proxyType: this.filters.proxyType
            };
            
            axios.get('/admin/api/proxies', { params })
                .then(response => {
                    console.log('代理数据响应:', response.data);
                    if (response.data && response.data.code === 200) {
                        const data = response.data.data || {};
                        // 检查数据结构并正确解析
                        if (data.list && Array.isArray(data.list)) {
                            // 需要对每个代理对象的字段进行处理，从后端返回的数据转为前端需要的格式
                            this.proxies = data.list.map(proxy => {
                                // 记录原始对象，用于调试
                                console.log('原始代理对象:', proxy);
                                
                                // 如果属性名已经是首字母大写的，就不需要转换
                                if (proxy.ProxyType) {
                                    return proxy;
                                }
                                
                                // 将小驼峰字段名转换为首字母大写格式
                                return {
                                    ID: proxy.id || proxy.ID,
                                    ProxyType: proxy.proxyType || proxy.proxy_type || "",
                                    ProxyIP: proxy.proxyIP || proxy.proxy_ip || "",
                                    ProxyPort: proxy.proxyPort || proxy.proxy_port || "",
                                    ProxyUser: proxy.proxyUser || proxy.proxy_user || "",
                                    ProxyPassword: proxy.proxyPassword || proxy.proxy_password || "",
                                    TagIDs: proxy.tagIDs || proxy.tag_ids || proxy.proxyTagID || "",
                                    Note: proxy.note || "",
                                    Active: proxy.active !== undefined ? proxy.active : true
                                };
                            });
                            
                            // 添加数据调试日志
                            console.log('处理后的代理列表:', this.proxies);
                        } else {
                            console.error('响应中没有有效的代理列表数据:', data);
                            this.proxies = [];
                        }
                        this.pagination.total = data.total || 0;
                    } else {
                        this.$message.error(response.data?.message || '加载失败');
                        this.proxies = [];
                    }
                })
                .catch(error => {
                    console.error('Error loading proxies:', error);
                    this.$message.error('加载代理失败，请检查网络连接');
                    this.proxies = [];
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        
        // 处理每页显示数量变化
        handleSizeChange(size) {
            this.pagination.pageSize = size;
            this.loadProxies();
        },
        
        // 处理页码变化
        handleCurrentChange(page) {
            this.pagination.page = page;
            this.loadProxies();
        },
        
        // 显示创建代理对话框
        showCreateProxyDialog() {
            this.isEditMode = false;
            this.dialogTitle = '添加代理';
            this.proxyForm = {
                id: '',
                proxyType: 'http',
                proxyIP: '',
                proxyPort: '',
                proxyUser: '',
                proxyPassword: '',
                proxyTagID: '',
                note: ''
            };
            this.proxyDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.proxyForm && this.$refs.proxyForm.clearValidate();
            });
        },
        
        // 显示更新代理对话框
        showUpdateProxyDialog(proxy) {
            this.isEditMode = true;
            this.dialogTitle = '编辑代理';
            this.proxyForm = {
                id: proxy.ID,
                proxyType: proxy.ProxyType,
                proxyIP: proxy.ProxyIP,
                proxyPort: proxy.ProxyPort,
                proxyUser: proxy.ProxyUser,
                proxyPassword: proxy.ProxyPassword,
                proxyTagID: proxy.TagIDs,
                note: proxy.Note
            };
            this.proxyDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.proxyForm && this.$refs.proxyForm.clearValidate();
            });
        },
        
        // 提交代理表单
        submitProxyForm() {
            this.$refs.proxyForm.validate(valid => {
                if (!valid) {
                    return false;
                }
                
                this.submitLoading = true;
                
                // 根据是否是编辑模式选择API
                const api = this.isEditMode ? '/admin/api/proxies' : '/admin/api/proxies';
                const method = this.isEditMode ? 'put' : 'post';
                
                axios[method](api, this.proxyForm)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.$message.success(response.data.message || '操作成功');
                            this.proxyDialogVisible = false;
                            this.loadProxies();
                        } else {
                            this.$message.error(response.data?.message || '操作失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error submitting proxy form:', error);
                        this.$message.error(`操作失败: ${error.response?.data?.message || error.message}`);
                    })
                    .finally(() => {
                        this.submitLoading = false;
                    });
            });
        },
        
        // 确认删除代理
        confirmDelete(proxy) {
            this.$confirm(`确定要删除代理 ${proxy.ProxyIP}:${proxy.ProxyPort} 吗?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteProxy(proxy.ID);
            }).catch(() => {
                // 用户取消删除
            });
        },
        
        // 删除代理
        deleteProxy(id) {
            this.loading = true;
            
            axios.delete(`/admin/api/proxies/${id}`)
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '删除成功');
                        this.loadProxies();
                    } else {
                        this.$message.error(response.data?.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error deleting proxy:', error);
                    this.$message.error(`删除失败: ${error.response?.data?.message || error.message}`);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        
        // 同步代理
        syncProxies() {
            this.loading = true;
            
            axios.post('/admin/api/proxies/sync')
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.syncResult = {
                            message: response.data.message,
                            total: response.data.data?.total || 0,
                            syncCount: response.data.data?.syncCount || 0
                        };
                        this.syncDialogVisible = true;
                        this.loadProxies();
                    } else {
                        this.$message.error(response.data?.message || '同步失败');
                    }
                })
                .catch(error => {
                    console.error('Error syncing proxies:', error);
                    this.$message.error(`同步失败: ${error.response?.data?.message || error.message}`);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        
        // 显示应用代理对话框
        showApplyProxyDialog(proxy) {
            this.currentProxy = proxy;
            this.applyProxyDialogVisible = true;
            this.applyResult = [];
            this.selectedUsers = [];
            this.selectAllUsers = false;
            this.userSearchKeyword = '';
            this.applyLoading = true;
            
            // 加载用户列表
            axios.get('/admin/api/users/composites')
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.users = response.data.data || [];
                    } else {
                        this.$message.error(response.data?.message || '加载用户列表失败');
                        this.users = [];
                    }
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    this.$message.error('加载用户列表失败');
                    this.users = [];
                })
                .finally(() => {
                    this.applyLoading = false;
                });
        },
        
        // 处理全选用户
        handleSelectAllUsers(val) {
            if (val) {
                // 全选用户
                this.selectedUsers = [...this.filteredUsers];
            } else {
                // 取消全选
                this.selectedUsers = [];
            }
        },
        
        // 处理用户选择变化
        handleUserSelectionChange(val) {
            this.selectedUsers = val;
            
            // 更新全选状态
            if (this.filteredUsers.length > 0) {
                this.selectAllUsers = val.length === this.filteredUsers.length;
            }
        },
        
        // 应用代理到用户
        applyProxyToUsers() {
            if (this.selectedUsers.length === 0) {
                this.$message.warning('请至少选择一个用户');
                return;
            }
            
            this.applyLoading = true;
            this.applyResult = [];
            
            // 收集所有用户ID
            const userIds = this.selectedUsers.map(user => user.userId);
            
            // 构造请求数据
            const requestData = {
                proxyId: this.currentProxy.ID,
                userIds: userIds
            };
            
            // 发送请求应用代理
            axios.post('/admin/api/proxies/apply-to-users', requestData)
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '应用代理成功');
                        this.applyResult = response.data.data || [];
                    } else {
                        this.$message.error(response.data?.message || '应用代理失败');
                    }
                })
                .catch(error => {
                    console.error('Error applying proxy:', error);
                    this.$message.error(`应用代理失败: ${error.response?.data?.message || error.message}`);
                })
                .finally(() => {
                    this.applyLoading = false;
                });
        },
        
        // 获取成功率
        getSuccessRate() {
            if (this.applyResult.length === 0) return '0%';
            
            const successCount = this.applyResult.filter(item => item.success).length;
            const rate = (successCount / this.applyResult.length * 100).toFixed(1);
            return `${rate}%`;
        }
    }
}); 